package com.davesandoval.tpdroid;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.sax.StartElementListener;

public class SoLogsdbAdapter {
	private SQLiteDatabase db;
	private DataBaseHelper dbHelper;
	private Context context;

	// Database fields
	public static final String KEY_ROW_ID = "_id";
	public static final String KEY_SO_NUM = "soNumber";
	public static final String KEY_LOG_DETAIL = "logDetail";
	public static final String KEY_START_TIME = "startTime";
	public static final String KEY_END_TIME = "endTime";
	public static final String KEY_START_DATE = "startDate";
	public static final String KEY_END_DATE = "endDate";
	public static final String KEY_NEW_STATUS = "newStatus";
	public static final String KEY_COPY_TO_WORK_PERFORMED = "copyToWorkPerformed";
	public static final String KEY_MARK_COMPLETE = "no";
	private static final String DATABASE_TABLE = "soLogs";

	// Default constructor
	public SoLogsdbAdapter(Context context) {
		this.context = context;
	}

	public SoLogsdbAdapter open() throws SQLException {
		dbHelper = new DataBaseHelper(context);
		db = dbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		dbHelper.close();
	}

	public long addSOLog(String soNumber, String logDetail, String startTime,
			String endTime, String startDate, String endDate, String newStatus,
			String copyToWorkPerformed, String markTaskAsCompleted) {
				ContentValues initialValues = createContentValues(soNumber, logDetail,
				startTime, endTime, startDate, endDate, newStatus,
				copyToWorkPerformed, markTaskAsCompleted);

		return db.insert(DATABASE_TABLE, null, initialValues);
	}

	private ContentValues createContentValues(String soNumber,
			String logDetail, String startTime, String endTime,
			String startDate, String endDate, String newStatus,
			String copyToWorkPerformed, String markTaskAsCompleted) {
				ContentValues values = new ContentValues();
				values.put(KEY_SO_NUM, soNumber);
				values.put(KEY_LOG_DETAIL, logDetail);
				values.put(KEY_START_TIME, startTime);
				values.put(KEY_END_TIME, endTime);
				values.put(KEY_START_DATE, startDate);
				values.put(KEY_END_DATE, endDate);
				values.put(KEY_NEW_STATUS, newStatus);
				values.put(KEY_COPY_TO_WORK_PERFORMED, copyToWorkPerformed);
				values.put(KEY_MARK_COMPLETE, markTaskAsCompleted);
				return values;
	}

	public Long fetchSOLogViaSONum(String soNum) throws SQLException {
		Cursor tempCursor = db.query(DATABASE_TABLE, null, KEY_SO_NUM + "="
				+ soNum, null, null, null, null);
		if (tempCursor != null) {
			tempCursor.moveToFirst();
		}
		return tempCursor.getLong(0);
	}

	public boolean isOpen() {
		return db.isOpen();
	}

}